package com.cloudkinto.service.workOrder.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.bo.workOrder.type.WorkOrderTypeAddBo;
import com.cloudkinto.bo.workOrder.type.WorkOrderTypeQueryBo;
import com.cloudkinto.bo.workOrder.type.WorkOrderTypeUpdateBo;
import com.cloudkinto.dao.WorkOrderTypeDao;
import com.cloudkinto.entity.WorkOrderTypeDo;
import com.cloudkinto.service.workOrder.WorkOrderTypeService;
import com.cloudkinto.vo.workOrder.WorkOrderTypeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 工单类型 service实现类
 * </p>
 *
 * @author long
 * @since 2025-01-07
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WorkOrderTypeServiceImpl extends ServiceImpl<WorkOrderTypeDao, WorkOrderTypeDo> implements WorkOrderTypeService {

    @Override
    public int add(WorkOrderTypeAddBo req) {
        WorkOrderTypeDo entityDo = new WorkOrderTypeDo();
        BeanUtils.copyProperties(req, entityDo);
        return baseMapper.insert(entityDo);
    }

    @Override
    public boolean update(WorkOrderTypeUpdateBo req) {
        return this.lambdaUpdate()
                .eq(WorkOrderTypeDo::getId, req.getId())
                .set(WorkOrderTypeDo::getName, req.getName())
                .update();
    }

    @Override
    public boolean updateEnable(Long id) {
        WorkOrderTypeDo workOrderTypeDo = this.getById(id);
        return this.lambdaUpdate()
                .eq(WorkOrderTypeDo::getId, id)
                .set(WorkOrderTypeDo::getEnable, !workOrderTypeDo.getEnable())
                .update();
    }

    @Override
    public List<WorkOrderTypeVo> getList(WorkOrderTypeQueryBo bo) {
        List<WorkOrderTypeDo> list = this.list(
                Wrappers.<WorkOrderTypeDo>lambdaQuery()
                        .eq(WorkOrderTypeDo::getTenantId, bo.getTenantId())
                        .eq(Objects.nonNull(bo.getEnable()), WorkOrderTypeDo::getEnable, bo.getEnable())
                        .orderByDesc(WorkOrderTypeDo::getId)
        );
        List<WorkOrderTypeVo> voList = JSONUtil.toList(JSONUtil.toJsonStr(list), WorkOrderTypeVo.class);
        voList.forEach(vo -> vo.setEnableStr(vo.getEnable() ? "激活" : "停用"));
        return voList;
    }
}
